# -*- coding: utf-8 -*-
#import cgi
import os
import re
import json
import time
import urllib2
import socket
from datetime import datetime
import pywintypes
# First import two useful modules
from win32com.client import Dispatch
#from adoconstants import *

def adjust():
	h=datetime.now().hour
	if(h>=0 and h<=6) or (h>=20 and h<=23):
		timecheck=3600
	else:
		timecheck=600
	return timecheck

def get_geo(car):
	geourl="http://maps.google.com/maps/api/geocode/json?latlng="+str(car["cl_lat"])+","+str(car["cl_lng"])+"&sensor=false&region=cn&language=zh-CN"
	print geourl
	req = urllib2.Request(geourl)
	try:
		response = urllib2.urlopen(req)
	except IOError,e:
		pass
	try:
		the_page = response.read()
		response.close()
	except socket.error:
		pass
	try:
		addr=json.loads(the_page)
		# print addr
		reverse=addr["results"][0]["formatted_address"];

		pattern=u'中国浙江省'
		reverse=re.sub(pattern,'',reverse)

		print reverse
		save_addr((str(car["clid"]),reverse))
		#print j
	except:
		#print "pass"
		pass

def writelog():
	logfilename=datetime.strftime(datetime.now(),"%Y%m%d")+".log"
	try:
		f=open('log'+os.sep+'getgeoaddr'+os.sep+logfilename,'a')
		try:
			f.write(datetime.strftime(datetime.now(),"%Y/%m/%d %H:%M:%S")+"\n")
		finally:
			f.close()
	except IOError:
		pass
		
def save_addr(car):
	oConn = Dispatch('ADODB.Connection')
	oConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=data\data.mdb;Jet OLEDB:Database Password=tp@chenkai"
	oConn.Open()
	oCmd = Dispatch('ADODB.Command')
	oCmd.ActiveConnection = oConn
	oCmd.CommandText = r"update cl set cl_reverse='"+car[1]+"' where clid="+car[0]
	print oCmd.CommandText
	oCmd.Execute()
	oCmd = None
	oConn.Close()
	oConn = None
	
def get_cars():
	cars=[]
	oConn = Dispatch('ADODB.Connection')
	oConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=data\data.mdb;Jet OLEDB:Database Password=tp@chenkai"
	oConn.Open()
	oRS = Dispatch('ADODB.RecordSet')
	oRS.ActiveConnection = oConn    # Set the recordset to connect thru oConn
	oRS.Open("select clid,cl_lng,cl_lat from cl where cl_speed<>0 and (cl_lat is not null or cl_lat<>'') and (cl_lng is not null or cl_lng<>'')")             # Open a table called zipcodeoCmd = Dispatch('ADODB.Command')
	while not oRS.EOF:
		car={}
		car["clid"]=oRS.Fields("clid").Value
		car["cl_lng"]=oRS.Fields("cl_lng").Value
		car["cl_lat"]=oRS.Fields("cl_lat").Value
		cars.append(car)
		oRS.MoveNext()
	print u"查找到的车辆：",cars
	oRS.Close()
	oRS=None
	oConn.Close()
	oConn=None
	return cars
	

while True:
	try:
		for car in get_cars():
			get_geo(car)
			time.sleep(5)
		writelog()
	except:
		pass
	time.sleep(adjust())


